package com.study.mall.product.service.impl;

import com.study.mall.product.service.CategoryBrandRelationService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.common.utils.PageUtils;
import com.study.common.utils.Query;

import com.study.mall.product.dao.CategoryDao;
import com.study.mall.product.entity.CategoryEntity;
import com.study.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    public List<CategoryEntity> listTree(){
        //1 所有的菜单
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //查找一级目录
        List<CategoryEntity> level1Entities = categoryEntities.stream().filter((entity) -> {
            return entity.getParentCid() == 0;
        }).collect(Collectors.toList());
        //查找一级目录对应二级目录
        level1Entities.stream().map((menu)->{
            menu.setChildren(getChildren(menu,categoryEntities));
            return menu;
        }).collect(Collectors.toList());
        return level1Entities;
    }

    /*
    级联更新
     */
    @Override
    public void updateCasCade(CategoryEntity category) {
        this.updateById(category);
        if (!Strings.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }

    }

    public List<CategoryEntity> getChildren(CategoryEntity category,List<CategoryEntity> allCategory){
//某个一级菜单的所有二级菜单
        List<CategoryEntity> collect = allCategory.stream().filter((menu) -> {
            return menu.getParentCid().equals(category.getCatId());
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, allCategory));
            return menu;
        }).collect(Collectors.toList());
        return collect;
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);


    }

}